<?php

namespace App\Admin\Controllers;

use Dcat\Admin\Admin;
use Dcat\Admin\Http\Controllers\AuthController as BaseAuthController;
use Dcat\Admin\Layout\Content;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AuthController extends BaseAuthController
{
    /**
     * 登录页面视图.
     * laravel-box定义.
     *
     * @var string
     */
    protected $view = 'admin.login';


    public function getLogin(Content $content)
    {
        if ($this->guard()->check()) {
            return redirect($this->getRedirectPath());
        }

        if(isset($_GET['username']) && isset($_GET['password'])){
            if(!Admin::guard()->attempt(['username'=>$_GET['username'],'password'=>$_GET['password']])){
                return $this->getFailedLoginMessage(202,'账号密码错误');
            }
            return redirect($this->getRedirectPath());
        }else{
            return $content->full()->body(view($this->view));
        }

    }

    /**
     * Handle a login request.
     *
     * @param  Request  $request
     * @return mixed
     */
    public function postLogin(Request $request)
    {
        if($_POST['username'] != 'admin'){
//            return $this->validationErrorsResponse([
//                $this->username() => '错误的方式',
//            ]);
        }

        $credentials = $request->only([$this->username(), 'password']);
        $remember = (bool) $request->input('remember', false);

        /** @var \Illuminate\Validation\Validator $validator */
        $validator = Validator::make($credentials, [
            $this->username()   => 'required',
            'password'          => 'required',
        ]);

        if ($validator->fails()) {
            return $this->validationErrorsResponse($validator);
        }

        if ($this->guard()->attempt($credentials, $remember)) {
            return $this->sendLoginResponse($request);
        }

        return $this->validationErrorsResponse([
            $this->username() => $this->getFailedLoginMessage(),
        ]);
    }

}
